package com.zs.admin.service.wisdbook.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.query.MPJQueryWrapper;
import com.zs.admin.service.wisdbook.IWisdbookPageMarkService;
import com.zs.admin.service.wisdbook.IWisdbookResourceService;
import com.zs.admin.validate.wisdbook.*;
import com.zs.admin.vo.wisdbook.WisdbookPageMarkDetailVo;
import com.zs.admin.vo.wisdbook.WisdbookPageMarkListedVo;
import com.zs.admin.vo.wisdbook.WisdbookPageMarkQuestListedVo;
import com.zs.common.config.GlobalConfig;
import com.zs.common.core.AjaxResult;
import com.zs.common.entity.wisdbook.WisdbookPage;
import com.zs.common.entity.wisdbook.WisdbookPageMark;
import com.zs.common.entity.wisdbook.WisdbookResource;
import com.zs.common.mapper.WisdbookPageMapper;
import com.zs.common.mapper.WisdbookPageMarkMapper;
import com.zs.common.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 智书标记块数据实现类
 * @author SwAdmin
 */
@Service
public class WisdbookPageMarkServiceImpl implements IWisdbookPageMarkService {
        
    @Resource
    WisdbookPageMarkMapper wisdbookPageMarkMapper;

    @Resource
    WisdbookPageMapper wisdbookPageMapper;

    @Resource
    IWisdbookResourceService iWisdbookResourceService;
    /**
     * 智书标记块数据列表
     *
     * @author SwAdmin
     * @param searchValidate 搜索参数
     * @return PageResult<WisdbookPageMarkListedVo>
     */
    @Override
    public AjaxResult list(WisdbookPageMarkSearchValidate searchValidate) {

        QueryWrapper<WisdbookPageMark> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("page_id", searchValidate.getPageId());
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByAsc("auto_id");

        wisdbookPageMarkMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "=:id:str",
            "=:pageId@page_id:int",
            "=:pid:str",
            "=:pPageId@p_page_id:int",
            "=:imgUrl@img_url:str",
            "=:shape:str",
            "=:featureType@feature_type:str",
            "=:markType@mark_type:str",
        });
        List<WisdbookPageMark> iPage = wisdbookPageMarkMapper.selectList(queryWrapper);
        List<WisdbookPageMarkListedVo> list = new LinkedList<>();
        for(WisdbookPageMark item : iPage) {
            WisdbookPageMarkListedVo vo = new WisdbookPageMarkListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setShape(JSONObject.parseObject(item.getShape()));
            List<WisdbookPageMarkListedVo> childs = new LinkedList<>();
            if(StringUtils.isEmpty(item.getPid()))
                childs = listByPid(vo.getId());
            vo.setChilds(childs);
            // 查询标记下挂接资源的总数
            WisdbookResourceSearchValidate resourceSearchValidate=new WisdbookResourceSearchValidate();
            resourceSearchValidate.setLinkType(0);
            resourceSearchValidate.setLinkId(item.getId());
            int resourceTotal= iWisdbookResourceService.total(resourceSearchValidate);

            vo.setResourceTotal(resourceTotal);
            list.add(vo);
        }
        return AjaxResult.success(list);
    }
    @Override
    public AjaxResult listQuest(WisdbookPageMarkSearchValidate searchValidate) {


        MPJQueryWrapper<WisdbookPageMark> mpjQueryWrapper = new MPJQueryWrapper<WisdbookPageMark>()
                .selectAll(WisdbookPageMark.class)
                .select("mq.quest_id","mq.id as mark_quest_id")
                .leftJoin("?_qd_mark_quest mq ON mq.mark_id=t.id".replace("?_", GlobalConfig.tablePrefix))
                .eq("t.is_delete", 0)
                .orderByAsc(Arrays.asList("t.auto_id"));

        wisdbookPageMarkMapper.setSearch(mpjQueryWrapper, searchValidate, new String[]{
                "=:id@t.id:str",
                "=:pageId@t.page_id:int",
                "=:pid@t.pid:str",
                "=:pPageId@t.p_page_id:int",
                "=:imgUrl@t.img_url:str",
                "=:shape@t.shape:str",
                "=:featureType@t.feature_type:str",
                "=:markType@t.mark_type:str",
        });
        List<WisdbookPageMarkQuestListedVo> iPage = wisdbookPageMarkMapper.selectJoinList(WisdbookPageMarkQuestListedVo.class,mpjQueryWrapper);

        List<WisdbookPageMarkQuestListedVo> ret =  iPage.stream().filter(wisdbookPageMarkQuestListedVo -> {
            return StringUtils.isEmpty(wisdbookPageMarkQuestListedVo.getPid());
        }).collect(Collectors.toList());
        return AjaxResult.success(ret);
    }
    /**
     * 智书标记块数据详情
     *
     * @author SwAdmin
     * @param pid pid参数
     * @return WisdbookPageMark
     */
    public List<WisdbookPageMarkListedVo> listByPid(String pid) {
        List<WisdbookPageMark> iPage = wisdbookPageMarkMapper.selectList(
                new QueryWrapper<WisdbookPageMark>()
                        .eq("pid", pid)
                        .eq("is_delete", 0)
                        .orderByAsc("auto_id"));

        List<WisdbookPageMarkListedVo> list = new LinkedList<>();
        for(WisdbookPageMark item : iPage) {
            WisdbookPageMarkListedVo vo = new WisdbookPageMarkListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setShape(JSONObject.parseObject(item.getShape()));
            vo.setChilds(new LinkedList<>());
            list.add(vo);
        }
        return list;
    }

    /**
     * 智书标记块数据详情
     *
     * @author SwAdmin
     * @param id 主键参数
     * @return WisdbookPageMark
     */
    @Override
    public WisdbookPageMarkDetailVo detail(String id) {
        WisdbookPageMark model = wisdbookPageMarkMapper.selectOne(
                new QueryWrapper<WisdbookPageMark>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");
        WisdbookPageMarkDetailVo vo = new WisdbookPageMarkDetailVo();
        BeanUtils.copyProperties(model, vo);
        vo.setShape(JSONObject.parseObject(model.getShape()));
        return vo;
    }

    /**
     * 智书标记块数据新增
     *
     * @author SwAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(WisdbookPageMarkCreateValidate createValidate) {
        WisdbookPageMark model = new WisdbookPageMark();
        model.setId(createValidate.getId());
        model.setPageId(createValidate.getPageId());
        model.setPid(createValidate.getPid());
        model.setPpageId(createValidate.getPpageId());
        model.setImgUrl(createValidate.getImgUrl());
        model.setShape(JSON.toJSONString(createValidate.getShape()));
        model.setFeatureType(createValidate.getFeatureType());
        model.setMarkType(createValidate.getMarkType());

        WisdbookPage wisdbookPage = wisdbookPageMapper.selectOne(
                new QueryWrapper<WisdbookPage>()
                        .eq("id", createValidate.getPageId())
                        .eq("is_delete", 0)
                        .last("limit 1"));
        Assert.notNull(wisdbookPage, "pageId数据不存在");

        model.setBookId(wisdbookPage.getBookId());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        wisdbookPageMarkMapper.insert(model);
    }

    /**
     * 智书标记块数据编辑
     *
     * @author SwAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(WisdbookPageMarkUpdateValidate updateValidate) {
        WisdbookPageMark model = wisdbookPageMarkMapper.selectOne(
                new QueryWrapper<WisdbookPageMark>()
                    .eq("id",  updateValidate.getId())
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setPageId(updateValidate.getPageId());
        model.setPid(updateValidate.getPid());
        model.setPpageId(updateValidate.getPpageId());
        model.setImgUrl(updateValidate.getImgUrl());
        model.setShape(JSON.toJSONString(updateValidate.getShape()));
        model.setFeatureType(updateValidate.getFeatureType());
        model.setMarkType(updateValidate.getMarkType());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        wisdbookPageMarkMapper.updateById(model);
    }

    /**
     * 智书标记块数据删除
     *
     * @author SwAdmin
     * @param id 主键ID
     */
    @Override
    public void del(String id) {
        WisdbookPageMark model = wisdbookPageMarkMapper.selectOne(
                new QueryWrapper<WisdbookPageMark>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setIsDelete(1);
        model.setDeleteTime(System.currentTimeMillis() / 1000);
        wisdbookPageMarkMapper.updateById(model);
    }

}
